import json
import os

import pymysql

from p2p.config import DIR_PATH

import logging.handlers


def read_json(filename,key):
    # 拼接读取文件的完整路径，os.sep动态获取/ \
    file_path=DIR_PATH+os.sep+"data"+os.sep+filename
    arr=[]
    with open(file_path,"r",encoding="utf-8") as f:
        for data in json.load(f).get(key):
            arr.append(tuple(data.values())[1:])
        return arr


# 日志工具
class GetLog:
    @classmethod
    def get_log(cls):
        cls.log=None
        if cls.log is None:
            # 1.获取日志器
            cls.log=logging.getLogger()
            # 设置日志级别 info
            cls.log.setLevel(logging.INFO)

            # 2.获取处理器 TimedRotatingFileHandler:日志保存到文件且根据时间去分割
            filepath=DIR_PATH+os.sep+"log"+os.sep+"p2p.log"
            tf=logging.handlers.TimedRotatingFileHandler(filename=filepath,
                                                         when="midnight",
                                                         interval=1,
                                                         backupCount=3,
                                                         encoding="utf-8")
            # 3.获取格式器
            fmt="%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)]-%(message)s"
            fm=logging.Formatter(fmt)

            # 4.将格式器添加到处理器中
            tf.setFormatter(fm)

            # 5.将处理器添加到日志器中
            cls.log.addHandler(tf)

            # 返回日志器
        return cls.log

# 读取htMl中的数据，用beautifulsoup4



# 连接库工具
def conn_mysql(sql):
    conn=None
    cursor=None

    try:
    #     1.获取连接对象
        conn=pymysql.connect(user="root",
            password="",
            host=None,port=3306,
                             charset="utf8",autocommit=True)
    # 2.获取游标对象
        cursor=conn.cursor()

    # 3.执行sql语句
        cursor.execute(sql)

        if sql.split()[0].lower()=="select":
            return cursor.fetchall()

        else:
            return cursor.rowcount

    except Exception as e:
        GetLog.get_log().error(e)
        raise

    finally:
        # 4.关闭游标
        cursor.close()

        # 5.关闭连接
        conn.close()

# 清除数据
def clear_data():
    sql=""""""
    conn_mysql(sql)



if __name__ == '__main__':
    sql="select * from mb_member"
    print(conn_mysql(sql))